package com.sqn.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.File;

/**
 * description: 异步任务
 *
 * @author sqn
 * @version 1.0
 * @date 2021/5/31 0031 上午 11:16
 */
@Service
public class AsyncService {

    @Autowired
    JavaMailSenderImpl mailSender;

    /**
     * description: 异步发送邮件
     * 使用 @Async 注解告诉Spring这是一个异步方法,SpringBoot就会自己开一个线程池，进行调用！
     *
     * @return: void
     * @author sqn
     * @date: 2021/5/31 0031 上午 11:29
     */
    @Async
    public void asyncTask() {
        try {
            System.out.println("业务处理开始");
            System.out.println("业务处理进行中");
            //邮件设置1：一个复杂的邮件
            MimeMessage mimeMessage = mailSender.createMimeMessage();
            MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage, true);

            messageHelper.setSubject("通知-国庆放假");
            messageHelper.setText("国庆放假时间:10.1-10.7 ......");

            //发送附件
            messageHelper.addAttachment("树奈奈.jpg", new File("D:\\IdeaProjects\\springboot-study\\async\\src\\main\\resources\\templates\\树奈奈.jpg"));
            messageHelper.addAttachment("獭獭.jpg", new File("D:\\IdeaProjects\\springboot-study\\async\\src\\main\\resources\\templates\\獭獭.jpg"));

            messageHelper.setTo("1334264094@qq.com");
            messageHelper.setFrom("1334264094@qq.com");

            mailSender.send(mimeMessage);

        } catch (MessagingException e) {
            e.printStackTrace();
        }
        System.out.println("业务处理结束");
    }
}
